<template>
  <div class="row">
    <div class="col-md-12">
      <!-- 选项卡导航 -->
      <ul class="nav nav-tabs mb-3">
        <li class="nav-item">
          <a class="nav-link" :class="{ active: activeTab === 'doi' }" href="#DOI" @click="handleTabClick('doi', $event)">
            Sci-Hub下载器
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" :class="{ active: activeTab === 'jiangsu' }" href="#JiangSu" @click="handleTabClick('jiangsu', $event)">
            江苏省审查报告下载器
          </a>
        </li>
      </ul>
      
      <!-- 选项卡内容 -->
      <div v-if="activeTab === 'doi'">
        <UploadArea />
      </div>
      <div v-else-if="activeTab === 'jiangsu'">
        <JiangSuUploadArea />
      </div>
      
      <!-- 任务列表 -->
      <TaskList />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue';
import UploadArea from '@/components/UploadArea.vue';
import JiangSuUploadArea from '@/components/JiangSuUploadArea.vue';
import TaskList from '@/components/TaskList.vue';
import { connectClientWebSocket, closeWebSocket } from '@/services/websocket';
import { useTaskStore } from '@/stores/taskStore';
import { fetchClientTasks } from '@/services/api';

const taskStore = useTaskStore();
const activeTab = ref('doi'); // 默认显示DOI下载器

// 处理tab点击事件
function handleTabClick(tab: string, event: Event) {
  // 不阻止默认行为，让浏览器更新URL hash
  switchTab(tab);
}

// 切换选项卡并加载对应类型的任务
async function switchTab(tab: string) {
  activeTab.value = tab;
  const taskType = tab === 'doi' ? 'DOI' : 'JiangSu';
  taskStore.setCurrentTaskType(taskType);
  await loadTasks(taskType);
}

// 根据URL hash更新activeTab
function updateTabFromHash() {
  const hash = window.location.hash.toLowerCase();
  if (hash === '#jiangsu') {
    switchTab('jiangsu');
  } else if (hash === '#doi' || hash === '') {
    switchTab('doi');
  }
}

// 监听hash变化
window.addEventListener('hashchange', updateTabFromHash);

onMounted(async () => {
  // 连接WebSocket
  connectClientWebSocket();
  
  // 根据URL hash设置初始tab
  updateTabFromHash();
});

onUnmounted(() => {
  // 关闭WebSocket连接
  closeWebSocket();
  
  // 移除hash变化监听器
  window.removeEventListener('hashchange', updateTabFromHash);
});

// 加载指定类型的任务
async function loadTasks(taskType: string = 'DOI') {
  try {
    const result = await fetchClientTasks(taskStore.clientId, taskType);
    if (result.status === 'success' && result.data) {
      // 清空当前类型的任务，以服务器数据为准
      taskStore.clearAllTasks(false); // 传入false表示不发送通知
      
      // 添加服务器返回的任务到内存中
      result.data.forEach(task => {
        // 确保任务有正确的类型
        task.task_type = taskType as 'DOI' | 'JiangSu';
        taskStore.addTask(task);
      });
      
      console.log(`成功从服务器加载 ${result.data.length} 个${taskType}任务`);
    }
  } catch (error) {
    console.error(`获取${taskType}任务失败:`, error);
  }
}
</script>